package com.zis.wechat.api.inter.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zis.starter.utils.HttpUtil;
import com.zis.wechat.api.config.WechatAPI;
import com.zis.wechat.api.config.WxConstant;
import com.zis.wechat.api.inter.IEventInter;
import com.zis.wechat.api.inter.IWechatInter;
import com.zis.wechat.api.model.EventScan;
import com.zis.wechat.model.TUser;
import com.zis.wechat.service.ITUserInter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Create by wangshen 2018/1/2
 */
@Service
@Transactional("txManager")
public class EventInterImpl implements IEventInter {

    private static final Logger logger = LoggerFactory.getLogger(EventInterImpl.class);

    @Autowired
    private IWechatInter wechatInter;

    @Autowired
    private ITUserInter itUserInter;

    /**
     * 用户关注
     * @param openId
     * @param accountId
     * @return
     * @throws Exception
     */
    @Override
    public String focus(String openId, String accountId) throws Exception {
        String url;
        String result;
        JSONObject jsonObj;
        String accessToken = wechatInter.getAccessToken(accountId);
        url = WechatAPI.getUserInfoUrl(accessToken,openId);
        result = HttpUtil.httpRequest(url, HttpUtil.METHOD_TYPE_GET, null);
        jsonObj = JSON.parseObject(result);
        if(jsonObj.containsKey("errcode")){
            logger.error(" >>> 获取微信用户信息错误："+ WxConstant.GLOBAL_ERROR_CODE.get(jsonObj.get("errcode")));
        }else{
            logger.debug(" >>> 已获取到用户信息："+jsonObj.toJSONString());
            TUser tUser = new TUser();
            tUser.setSubscribe(jsonObj.getString("subscribe"));//是否关注
            tUser.setOpenId(jsonObj.getString("openid"));//openId
            tUser.setNickName(URLEncoder.encode(jsonObj.getString("nickname")));//昵称 转义存储
            tUser.setSex(jsonObj.getString("sex"));//性别
            tUser.setCity(jsonObj.getString("city"));
            tUser.setCountry(jsonObj.getString("country"));
            tUser.setProvince(jsonObj.getString("province"));
            tUser.setLanguage(jsonObj.getString("language"));
            tUser.setHandimgUrl(jsonObj.getString("headimgurl"));
            tUser.setSubscribeTime(jsonObj.getString("subscribe_time"));
            tUser.setUnionid(jsonObj.getString("unionid"));
            tUser.setRemarks(jsonObj.getString("remark"));
            tUser.setAccountId(accountId);
            //设置系统级别参数
            tUser.setIsFocus("1");
            tUser.setFocusTime(new Date());
            //查询用户关注信息是否存在
            Map<String, Object> params = new HashMap<>();
            params.put("openId", jsonObj.getString("openid"));
            params.put("accountId", accountId);
            List<TUser> tUserList = itUserInter.findByCondition(params);
            if(tUserList.size() > 0){
                tUser.setTuId(tUserList.get(0).getTuId());//设置更新的主键
                itUserInter.update(tUser);
            }else{
                //新增设置业务状态为未认证 -1;
                tUser.setAuthBuss("-1");
                itUserInter.insert(tUser);
            }
            //调用回复消息
            return wechatInter.focusMsg(accountId,openId);
        }
        return "fail";
    }

    /**
     * 用户取消关注
     * @param openId
     * @param accountId
     * @return
     * @throws Exception
     */
    @Override
    public String unFocus(String openId, String accountId) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("openId", openId);
        params.put("accountId", accountId);
        List<TUser> tUserList = itUserInter.findByCondition(params);
        if(tUserList.size() > 0){
            String tuId = tUserList.get(0).getTuId();
            TUser tUser = new TUser();
            tUser.setTuId(tuId);
            tUser.setSubscribe("0");
            tUser.setIsFocus("0");
            itUserInter.update(tUser);
            return "";
        }
        return "fail";
    }

    /**
     * 用户扫描二维码
     * @param eventScan
     * @return
     * @throws Exception
     */
    @Override
    public String scanQrCode(EventScan eventScan) throws Exception {
        return null;
    }
}
